﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using Utils;
using Utils.Buffer;

namespace Microsoft.AspNetCore.Mvc
{
    public static class ControllerHelper
    {
        public static Verify<T> Verify<T>(this ControllerBase controllerBase, T obj)
        {
            return new Verify<T>(obj);
        }


        public static bool IsToken<T>(this ControllerBase controllerBase) where T : AuthIdentity
        {
            return controllerBase.HttpContext.User.Identity.AuthenticationType == typeof(T).FullName;
        }

        public static AuthIdentity GetUserToken(this ControllerBase controllerBase)
        {
            return GetUserToken<AuthIdentity>(controllerBase);
        }


        public static T GetUserToken<T>(this ControllerBase controllerBase) where T : AuthIdentity
        {
            if (controllerBase.User.Identity is T res)
            {
                return res;
            }
            return null;
        }
         
        public static string CreartTicket(this ControllerBase controllerBase, AuthIdentity userToken, long expired = 3600 * 24 * 7)
        {
            return userToken.ToTokenString(expired);
        }

        public static DateTime?[] GetTimeRange(this ControllerBase controllerBase)
        {
            return controllerBase.Request.Query["timeRange[]"].Select(a => a.IsNullOrEmpty() ? null : a?.ToDateTime()).ToArray();
        }

   
        public static AuthIdentity CreateByToken(this HttpRequest httpRequest, bool allowAnonymous)
        {
            return AuthIdentity.CreateByToken(httpRequest.HttpContext.RequestServices, GetToken(httpRequest), allowAnonymous);
        }


        /// <summary>
        /// 获得服务器的ip地址
        /// </summary>
        /// <returns>ip地址</returns>
        public static string GetServerIP(this HttpRequest httpRequest)
        {
            if (httpRequest.Headers.TryGetValue("Local_Addr", out Microsoft.Extensions.Primitives.StringValues value))
            {
                return value.FirstOrDefault();
            }
            return "127.0.0.1";
        }


        /// <summary>
        /// 获得客户端的ip地址
        /// </summary>
        /// <returns>ip地址</returns>
        public static string GetClientIP(this HttpRequest httpRequest)
        {
            try
            {
                if (httpRequest.Headers.TryGetValue("X-real-ip", out Extensions.Primitives.StringValues value1) && value1.Count > 0)
                {
                    return value1.ToString();
                }

                if (httpRequest.Headers.TryGetValue("X-Forwarded-For", out Extensions.Primitives.StringValues value) && value.Count > 0)
                {
                    return value.FirstOrDefault();
                }
                return httpRequest.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            }
            catch (Exception)
            {
                return "0.0.0.0";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static string GetToken(HttpRequest request)
        {
            if (request.Query.ContainsKey("access_token"))
            {
                return request.Query["access_token"];
            }
            if (request.Headers.ContainsKey("access-token"))
            {
                return request.Headers["access-token"].ToString();
            }
            if (request.Headers.ContainsKey("Authorization"))
            {
                return request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            }
            if (request.Cookies.ContainsKey("access-token"))
            {
                return HttpUtility.UrlDecode(request.Cookies["access-token"]);
            }
            return null;
        }



    }
}
